import {supportFunction} from "../../utils/supportFunction";
import {ModuleRender} from "../render/ModuleRender";
import {stringUtils} from "../../utils/stringUtils";
import {MidwayConfig} from "../midway";
import {requestParams} from "../../utils/request";

export const controlMethod = {
    BEFORE_RUN: 'processBeforeRun',
    AFTER_RUN: 'processAfterRun'
};
export const lifecycleMethod = {
    render: ["beforeRender"],
    run: ["beforeRun", "run", "afterRun"],
    update: ["update"],
    show: ["pageShow"],
    destroy: ["destroy"]
};

export class ModuleProcessor {
    constructor(options) {
        this._instance = options.instance;
        this._context = options.context;

        this._key = stringUtils.randomWord(false, 8);
        this._code = options.code;
        this._style = options.style;
        this._container = options.container;
        this._model = options.model;
        this._view = options.template;

        this._hasRunning = {};
        this._isController = isController(this._instance);
    }

    get ModuleInstance() {
        return this._instance;
    }

    get ModuleCode() {
        return this._code;
    }

    get ProcessorKey() {
        return this._key;
    }

    get RunningModules() {
        return this._hasRunning;
    }

    get IsController() {
        return this._isController;
    }

    set Model(model) {
        if(model) {
            this._model = model;
        }
    }

    render(attributes) {
        ModuleRender.render(this._key, this._code, this._style, this._view, this._container, attributes);
    }

    /**
     * @summary 执行生命周期前方法, 方法皆为同步过程
     */
    runInit() {
        supportFunction.execute(this._instance, {
            'setPlayerController': this._context,
            'setUrlParams': requestParams.get(),
            'setBasePath': MidwayConfig.BasePath
        });
    }

    /**
     * 执行生命周期方法
     * @param lifecycle 生命周期
     * @extend 扩展方法参数
     * @
     * @returns {*}
     */
    runLifecycle(lifecycle) {
        let taskList = [];
        lifecycle.forEach(name => {
            taskList.push({
                fn: this._instance[name],
                args: [this._view, this._model],
                scope: this._instance,
                name: ""
            });
        });
        return supportFunction.runSequence(taskList, "run bundle lifecycle");
    }
}

function isController(instance) {
    return !!(instance[controlMethod.BEFORE_RUN] && instance[controlMethod.AFTER_RUN]);
}